﻿#include "StdAfx.h"
#include "Timer.h"

Timer::Timer()
{
    //Initialize the variables
    startTicks = 0;
    pausedTicks = 0;
    paused = false;
    started = false;    
}
void Timer::start()
{
    //Start the timer
    started = true;
    
    //Unpause the timer
    paused = false;
    
    //Get the current clock time
    startTicks = SDL_GetTicks();    
}
void Timer::stop()
{
    //Stop the timer
    started = false;
    
    //Unpause the timer
    paused = false;    
}
int Timer::get_ticks()
{
    //If the timer is running
    if( started == true )
    {
        //If the timer is paused
        if( paused == true )
        {
            //Return the number of ticks when the timer was paused
            return pausedTicks;
        }
        else
        {
            //Return the current time minus the start time
            return SDL_GetTicks() - startTicks;
        }    
    }
    
    //If the timer isn't running
    return 0;    
}
void Timer::pause()
{
    //If the timer is running and isn't already paused
    if( ( started == true ) && ( paused == false ) )
    {
        //Pause the timer
        paused = true;
    
        //Calculate the paused ticks
        pausedTicks = SDL_GetTicks() - startTicks;
    }
}
void Timer::unpause()
{
    //If the timer is paused
    if( paused == true )
    {
        //Unpause the timer
        paused = false;
    
        //Reset the starting ticks
        startTicks = SDL_GetTicks() - pausedTicks;
        
        //Reset the paused ticks
        pausedTicks = 0;
    }
}
bool Timer::is_started()
{
    return started;    
}

bool Timer::is_paused()
{
    return paused;    
}
////////////////////////////////////////////////////////
//추후 다른 클래스로 포함 또는 분리 필요
//FPS 계산 및 딜레이 처리
////////////////////////////////////////////////////////
wchar_t * Timer::RegulateFps(int fps_limit)
{

	//경과시간 읽어오기
	int elapsedTicks = this->get_ticks();

	//목표보다 빠르면 지연
	if(1000 > (fps_limit * elapsedTicks))
	{
		int delay = 1000 / fps_limit - elapsedTicks;
		SDL_Delay(delay);
	}
	elapsedTicks = this->get_ticks();
	//fps 계산
	float fps = (float)1000/ elapsedTicks;

	swprintf(this->output, L"%.1f", fps);
	this->start();
	return output;
}
Timer::~Timer(void)
{
}
